import subprocess
import configparser
from flask import jsonify, request,Blueprint
download_bp = Blueprint('download_bp', __name__)

config = None

def read_config(config_file='config/download.ini'):
    global config
    config = configparser.ConfigParser()
    config.read(config_file)
    if 'baidu_cloud' in config:
        username = config['baidu_cloud'].get('username')
        password = config['baidu_cloud'].get('password')
        return username, password
    else:
        return None, None


def login_baidu_cloud():
    if config is None:
        return False
    username = config['baidu_cloud'].get('username')
    password = config['baidu_cloud'].get('password')
    try:
        command = f'baidupcs-py login -u "{username}" -p "{password}"'
        result = subprocess.run(command, shell=True, check=True, text=True, capture_output=True)
        print("登录成功！")
        print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"登录失败: {e.stderr}")
        return False


def read_baidu_cloud_file(remote_path):
    try:
        command = f'baidupcs-py cat "{remote_path}"'
        result = subprocess.run(command, shell=True, check=True, text=True, capture_output=True)
        file_content = result.stdout
        return file_content
    except subprocess.CalledProcessError as e:
        print(f"读取文件失败: {e.stderr}")
        return None


def read_file_route():
    data = request.get_json()
    remote_path = data.get('remote_path')
    if not remote_path:
        return jsonify({'message': '缺少远程文件路径参数'}), 400

    username, password = read_config()
    if not all([username, password]):
        return jsonify({'message': '配置文件中缺少必要信息'}), 400

    if not login_baidu_cloud(username, password):
        return jsonify({'message': '百度云登录失败'}), 500

    file_content = read_baidu_cloud_file(remote_path)
    if file_content is None:
        return jsonify({'message': '读取文件失败'}), 500

    return jsonify({'message': '文件读取成功', 'content': file_content}), 200
@download_bp.route('/download_file', methods=['POST'])
def download_file():
    data = request.get_json()
    remote_path = data.get('remote_path')
    if not remote_path:
        return jsonify({'message': '缺少远程文件路径参数'}), 400
    return download_file_api(remote_path)
def download_file_api(remote_path):
    username=config['baidu_cloud'].get('username');
    password=config['baidu_cloud'].get('password');
    if username is None or password is None:
        return jsonify({'message': '配置文件中缺少必要信息'}), 400

    if not login_baidu_cloud():
        return jsonify({'message': '百度云登录失败'}), 500

    file_content = read_baidu_cloud_file(remote_path)
    if file_content is None:
        return jsonify({'message': '读取文件失败'}), 500

    return jsonify({'message': '文件读取成功', 'content': file_content}), 200
read_config()
